package com.hdu.careerplan.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.careerplan.configuration.FilepathConfiguration;
import com.hdu.careerplan.mapper.*;
import com.hdu.careerplan.pojo.dto.EmployerLoginDTO;
import com.hdu.careerplan.pojo.dto.EmployerRegisterDTO;
import com.hdu.careerplan.pojo.dto.ScreenResumeDTO;
import com.hdu.careerplan.pojo.entity.*;
import com.hdu.careerplan.pojo.vo.QualifiedResumeVO;
import com.hdu.careerplan.pojo.vo.UserWholeInfoVO;
import com.hdu.careerplan.service.EmployerService;
import com.hdu.careerplan.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
* @author 10240
* @description 针对表【employee】的数据库操作Service实现
* @createDate 2024-03-17 21:37:40
*/
@Slf4j
@Service
public class EmployerServiceImpl extends ServiceImpl<EmployerMapper, Employer>
    implements EmployerService {

    @Resource
    private EmployerMapper employerMapper;
    @Resource
    private ResumeMapper resumeMapper;

    @Resource
    private UserBasicInfoMapper userBasicInfoMapper;

    @Resource
    private UserEducationInfoMapper userEducationInfoMapper;

    @Resource
    private UserBriefInfoMapper userBriefInfoMapper;

    @Resource
    private CompetenceInfoMapper competenceInfoMapper;

    @Override
    public int register(EmployerRegisterDTO employerRegisterDTO) {
        String phone = employerRegisterDTO.getPhone();
        String code = employerRegisterDTO.getCode();

        log.info("employee register service");

        //2.查找有没有被注册过，工号和手机号都应该是唯一的
        QueryWrapper<Employer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone).or().eq("code", code);
        Long count = employerMapper.selectCount(queryWrapper);
        if (count > 0) {
            return -1;
        }

        //3. 加密密码
        Employer employer = new Employer();
        employer.setPassword(PasswordUtil.encryptPassword(employerRegisterDTO.getPassword()));
        employer.setPhone(phone);
        employer.setCode(code);

        int insertSituation = employerMapper.insert(employer);
        if (insertSituation == 1) {
            return 0;
        }
        return -1;

    }

    @Override
    public Employer login(EmployerLoginDTO employerLoginDTO) {
        log.info("employee login service");
        QueryWrapper<Employer> queryWrapper = new QueryWrapper<>();
        String s = PasswordUtil.encryptPassword(employerLoginDTO.getPassword());
        queryWrapper.eq("phone", employerLoginDTO.getPhone()).eq("password", PasswordUtil.encryptPassword(employerLoginDTO.getPassword()));
        return employerMapper.selectOne(queryWrapper);
    }

    @Override
    public File downloadResume(Long userId, Long employerId) {
        //1. 先查找有没有上传简历
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Resume> resumes = resumeMapper.selectList(queryWrapper);

        //2. 数据出错1，即失败
        if (resumes.size() != 1) {
            log.info("没有上传简历");
            return null;
        }

        //3. 没有问题，判断文件在不在
        String fileName = resumes.get(0).getUuid();
        String completedFilePath = FilepathConfiguration.storageDirPath + fileName;
        File file = new File(completedFilePath);
        //4. 文件不存在
        if(!file.exists()){
            log.info("简历文件丢失，文件位置：{}", completedFilePath);
            return null;
        }

        log.info("工作人员工号：{}，下载了用户id为{}的简历", employerId, userId);
        return file;
    }

    @Override
    public UserWholeInfoVO getUserInfoById(Long userId, Long employerId) {
        //TODO ZHR 2024.3.18 查了三次表，太多了
        //1. 基本信息
        QueryWrapper<UserBasicInfo> queryWrapperForBasic = new QueryWrapper<>();
        queryWrapperForBasic.eq("user_id", userId);
        UserBasicInfo userBasicInfo = userBasicInfoMapper.selectOne(queryWrapperForBasic);

        //2. 教育信息
        QueryWrapper<UserEducationInfo> queryWrapperForEducation = new QueryWrapper<>();
        queryWrapperForEducation.eq("user_id", userId);
        UserEducationInfo userEducationInfo = userEducationInfoMapper.selectOne(queryWrapperForEducation);

        //3. 简历信息
        QueryWrapper<Resume> queryWrapperForResume = new QueryWrapper<>();
        queryWrapperForResume.eq("user_id", userId)
                .select("directions","skills","self_evaluation","internships","projects","competitions");
        Resume resume = resumeMapper.selectOne(queryWrapperForResume);

        //4. 装配
        UserWholeInfoVO userWholeInfoVO = new UserWholeInfoVO();
        userWholeInfoVO.setBasic(userBasicInfo);
        userWholeInfoVO.setEducation(userEducationInfo);
        userWholeInfoVO.setResume(resume);

        log.info("工作人员工号：{}，查看了用户id为{}的完整信息", employerId, userId);
        return userWholeInfoVO;
    }

    @Override
    // 优化连表查询
    public QualifiedResumeVO screenResume(ScreenResumeDTO screenResumeDTO, Long employerId) {
        Integer page = screenResumeDTO.getPage();
        Integer size = screenResumeDTO.getSize();
        String direction = screenResumeDTO.getDirection();
        List<String> skills = screenResumeDTO.getSkills();
        // 1.什么都没有选择，直接返回null
        if (direction.isEmpty() && skills.isEmpty()) {
            log.info("没有选择任何选项");
            return null;
        }
        // 2. 只要选择了方向，则以方向为准，方向去查胜任度的表 //TODO ZHR 2024.3.19 策略的改进
        if (!direction.isEmpty()) {
            // 2.1 分页查询，符合方向的评分从高到低
            QueryWrapper<CompetenceInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("user_id").eq("direction", direction).orderByDesc("score");
            Page<CompetenceInfo> competenceInfoPage = competenceInfoMapper.selectPage(new Page<>(page, size), queryWrapper);
            List<CompetenceInfo> records = competenceInfoPage.getRecords();

            //TODO ZHR 2024.03.18 优化查询，不用MP，只取一列，且按照该列顺序去取数据，连表查询
            //2.2 遍历得到user_id,通过user_id去查对应的信息
            List<UserBriefInfo>  qualifiedApplicants = new ArrayList<>();
            for (CompetenceInfo record : records) {
//                System.out.println(record.getUserId());
                QueryWrapper<UserBriefInfo> userBriefInfoQueryWrapper = new QueryWrapper<>();
                userBriefInfoQueryWrapper.eq("user_id", record.getUserId());
                UserBriefInfo userBriefInfo = userBriefInfoMapper.selectOne(userBriefInfoQueryWrapper);
                if (userBriefInfo != null) qualifiedApplicants.add(userBriefInfo);
            }
//            System.out.println("-----");
            // 2.3 封装
            QualifiedResumeVO qualifiedResumeVO = new QualifiedResumeVO();
            qualifiedResumeVO.setTotal((int) competenceInfoPage.getTotal());
            qualifiedResumeVO.setData(qualifiedApplicants);
            return qualifiedResumeVO;
        }

        // 3. 若没有选择方向，这以技术点作为筛选条件，
        List<String> skillJsons = new ArrayList<>();
        for (String skill : skills) {
            // 3.1 将每一个技术点转换为符合json列表的格式
            List<String> skillJsonTemp = new ArrayList<>();
            skillJsonTemp.add(skill);
            skillJsons.add(JSON.toJSON(skillJsonTemp).toString());
        }
        // 3.2 包含任一技术的总人数
        int totalCount = resumeMapper.countUsersBySkills(skillJsons);
        int offset = (page - 1 ) * size;

        // 3.3 分页设置不合理的情况，返回为0
        if (offset > totalCount) {
            QualifiedResumeVO qualifiedResumeVO = new QualifiedResumeVO();
            qualifiedResumeVO.setTotal(0);
            List<UserBriefInfo> qualifiedApplicants = new ArrayList<>();
            qualifiedResumeVO.setData(qualifiedApplicants);
            return qualifiedResumeVO;
        }

        // 3.4 分页设置合理的情况，按照匹配上的技术个数进行倒序排序
        //TODO ZHR 2024.03.18 优化查询，按照该列顺序去取数据，连表查询
        List<Integer> qualifiedUserIdList= resumeMapper.findUsersWithSkills(skillJsons, offset, size);

        // 3.5 按照顺序去查找个人简要信息
        List<UserBriefInfo>  qualifiedApplicants = new ArrayList<>();
        for (Integer qualifiedUserId : qualifiedUserIdList) {
//                System.out.println(record.getUserId());
            QueryWrapper<UserBriefInfo> userBriefInfoQueryWrapper = new QueryWrapper<>();
            userBriefInfoQueryWrapper.eq("user_id", qualifiedUserId);
            UserBriefInfo userBriefInfo = userBriefInfoMapper.selectOne(userBriefInfoQueryWrapper);
            if (userBriefInfo != null) qualifiedApplicants.add(userBriefInfo);
        }

        // 3.6 封装
        QualifiedResumeVO qualifiedResumeVO = new QualifiedResumeVO();
        qualifiedResumeVO.setTotal(totalCount);
        qualifiedResumeVO.setData(qualifiedApplicants);
        return qualifiedResumeVO;
    }
}




